<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>欢饮</div>
    <div id="dom"></div>
    <button onclick="sendHandle()">发送消息</button>
    <script>
      const dome = document.getElementById("dom");
      const messages = [];
      const socket = new WebSocket("ws://localhost:8080");
      // 连接websocket
      const connectWebSocket = () => {
        // 连接成功
        socket.onopen = () => {
          console.log("连接成功！！！");
        };
        // 接收消息
        socket.onmessage = (e) => {
          messages.push(e.data);
          dome.innerHTML = messages.join("<br />");
        };
      };
      connectWebSocket();
      // 发送消息
      function sendHandle() {
        if (socket.readyState !== 1) {
          console.log("连接未建立");
          return;
        } else {
          socket.send("hello");
          console.log("发送成功！！！");
        }
      }
    </script>
  </body>
</html>
